package controller

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-api/app/global"
	"go-api/app/logic/ai"
	"go-api/app/request"
	"go-api/internal/response"
	"net/http"
)

type Ai struct {
	G *global.Global
}

func (a Ai) Chat(c *gin.Context) {
	var req request.AiChatRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		status, ar := response.ApiResponse(nil, err)
		c.JSON(status, ar)
		return
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	stream := make(chan *ai.ChatReply)
	go a.G.AiChat.Question(ctx, req.Question, stream)

	flusher, ok := c.Writer.(http.Flusher)
	if !ok {
		status, ar := response.ApiResponse(nil, errors.New("流式传输失败"))
		c.JSON(status, ar)
		return
	}

	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")

	for {
		chatReply := <-stream

		_, ar := response.ApiResponse(chatReply, chatReply.Err)
		j, _ := json.Marshal(ar)
		fmt.Fprintf(c.Writer, "data: %s\n\n", j)

		flusher.Flush() // 发送数据到客户端并刷新缓冲区

		if chatReply.Status == 2 {
			break
		}
	}
}

func NewAiController(g *global.Global) Ai {
	return Ai{G: g}
}
